package com.example.a2032.Utils;


import android.util.Base64;
import android.util.Log;


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author Administrator
 */
public class AesTest {


    public final static String KEY_AES = "qwA3v5mzo0PH84mA";

    // 加密
    public static String Encrypt(String sSrc) throws Exception {

        byte[] raw = KEY_AES.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        //此处使用BASE64做转码功能，防止密文转换为字符串后内容改变。
        return Base64.encodeToString(encrypted, Base64.NO_WRAP);
    }

    // 解密
    public static String Decrypt(String sSrc) throws Exception {
        try {
            // 判断Key是否正确

            byte[] raw = KEY_AES.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            //先用base64解密
            byte[] encrypted1 = Base64.decode(sSrc, Base64.DEFAULT);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                return new String(original, "utf-8");
            } catch (Exception e) {
                Log.e(TAG, "Decrypt: " + e.toString());

                return null;
            }
        } catch (Exception ex) {
            Log.e(TAG, "Decrypt: " + ex.toString());
            return null;
        }
    }

    private static final String TAG = "AesTest";

}
